from urllib.parse import urlparse

BYTES = {'LF': '\x0A', 'NULL': '\x00'}

class Frame:
    def __init__(self, command, headers, body=''):
        self.command = command
        self.headers = headers
        self.body = body

    def __str__(self):
        lines = [self.command]

        skip_content_length = ('content-length' in self.headers)
        if skip_content_length:
            del self.headers['content-length']
        
        for header in self.headers:
            value = self.headers[header]
            lines.append(header + ':' + value)

        if not skip_content_length:
            lines.append('content-length:' + str(len(self.body)))

        lines.append(BYTES['LF'] + self.body)
        return BYTES['LF'].join(lines)

    @staticmethod
    def unmarshall(data):
        lines = data.split(BYTES['LF'])
        command = lines[0].strip()

        headers = {}
        i = 1
        while lines[i] != '': # See __str__ you'll know why
            k, v = lines[i].split(':')
            headers[k] = v
            i += 1

        body = '' if lines[i + 1] == BYTES['NULL'] else lines[i + 1][:-1]

        return Frame(command, headers, body)

    @staticmethod
    def marshall(command, headers, body):
        return str(Frame(command, headers, body)) + BYTES['NULL']